package com.czk.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * mybatis工具类
 * @Author:ChenZhangKun
 * @Date: 2020/12/10 21:41
 */
public class MybatisUtils {
    /**
     * SqlSessionFactory全局仅此一份应该设置成单例模式
     */
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            // 加载全局配置文件
            String resource= "mybatis-config.xml";
            //
            InputStream inputStream = Resources.getResourceAsStream(resource);
            // 创建工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }

    /**
     * 返回sqlsession
     * @return
     */
    public static SqlSession getSqlSession(){
        // sqlSession是线程不安全的，不能被线程共享，每个线程应该有单独的sqlSession,用完应当关闭，不然造成资源浪费
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}
